import React, { useEffect, useRef, useState } from "react";
import { Card, Avatar, List, Input, Button, Space, Upload, message as antdMsg } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import type { ConsultMessage, ConsultSession } from "../../types/consult";
import { useParams } from "react-router-dom";

// 模拟医生数据
const mockDoctors = [
  { id: "doc1", name: "王医生", type: "doctor", avatar: undefined, department: "骨科" },
  { id: "doc2", name: "李医生", type: "doctor", avatar: undefined, department: "康复科" },
  { id: "doc3", name: "张医生", type: "doctor", avatar: undefined, department: "神经内科" }
];

// 模拟会话数据
const createMockSession = (doctorId: string): ConsultSession => {
  const doctor = mockDoctors.find(d => d.id === doctorId) || mockDoctors[0];
  return {
    id: "s1",
    patient: { id: "p1", name: "张三", type: "patient" },
    doctor: doctor,
    status: '进行中',
    lastMessage: null,
    messages: [
      { id: 'm1', sessionId: 's1', senderId: doctor.id, senderType: 'doctor', type: 'text', content: '您好，有什么需要咨询？', sendTime: '2024-06-07 09:00' },
      { id: 'm2', sessionId: 's1', senderId: 'p1', senderType: 'patient', type: 'text', content: '我最近膝盖疼。', sendTime: '2024-06-07 09:01' }
    ],
    createdAt: '2024-06-07 09:00',
    updatedAt: '2024-06-07 09:10',
  };
};

const ConsultChat: React.FC = () => {
  const { id } = useParams();
  // 根据路由参数获取医生ID，如果没有则使用默认值
  const doctorId = id || "doc1";
  const session = createMockSession(doctorId);
  const [messages, setMessages] = useState<ConsultMessage[]>(session.messages);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const msgEndRef = useRef<HTMLDivElement>(null);
  // 模拟WebSocket: 消息本地追加
  const send = (msg: Partial<ConsultMessage>) => {
    setSending(true);
    setTimeout(() => {
      setMessages(msgs => [...msgs, {
        id: Date.now()+Math.random()+'',
        sessionId: session.id,
        senderId: 'p1',
        senderType: 'patient',
        type: msg.type||'text',
        content: msg.content||'',
        sendTime: new Date().toLocaleString()
      }]);
      setSending(false);
      // 模拟医生回复
      setTimeout(() => {
        const replies = [
          '了解，请问这种情况持续多久了？',
          '有没有受过外伤或者做过剧烈运动？',
          '建议您先减少活动，注意休息。',
          '可以考虑热敷缓解症状。',
          '如果疼痛加重，建议及时来院检查。'
        ];
        const randomReply = replies[Math.floor(Math.random() * replies.length)];
        setMessages(msgs => [...msgs, {
          id: Date.now()+Math.random()+'',
          sessionId: session.id,
          senderId: session.doctor.id,
          senderType: 'doctor',
          type: 'text',
          content: randomReply,
          sendTime: new Date().toLocaleString()
        }]);
      }, 1000);
    }, 500);
  };
  // 滚动到底部
  useEffect(() => { msgEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]);
  // 上传图片
  const beforeUpload = (file:any) => {
    setSending(true);
    setTimeout(() => {
      send({ type:'image', content:'https://via.placeholder.com/100?rand='+Math.random() })
      setSending(false);
    }, 1000);
    return false;
  };
  return (
    <Card
      style={{ maxWidth: 700, margin: '0 auto', marginTop: 20 }}
      title={<Space><Avatar>{session.doctor.name[0]}</Avatar><span>{session.doctor.name}（{session.doctor.department}）</span></Space>}
      bodyStyle={{ padding: 12, minHeight: 360 }}
    >
      <List
        dataSource={messages}
        renderItem={m => (
          <List.Item style={{ justifyContent: m.senderType==='patient'? 'flex-end':'flex-start', border: 'none' }}>
            <Space direction={m.senderType==='patient'?'rtl':'ltr'}>
              <Avatar>{m.senderType==='doctor'?session.doctor.name[0]:'我'}</Avatar>
              {m.type==='text'?
                <span style={{ background: '#f6ffed', borderRadius: 8, padding: '8px 12px', maxWidth: 260, display: 'inline-block' }}>{m.content}</span>
                :
                <img src={m.content} alt="pic" style={{ maxWidth: 100, borderRadius: 6, border: '1px solid #eee' }} />
              }
            </Space>
          </List.Item>
        )}
      />
      <div ref={msgEndRef} />
      <Space style={{width:'100%',marginTop:16}} align="start">
        <Input.TextArea value={input} onChange={e=>setInput(e.target.value)} autoSize={{minRows:1,maxRows:3}} style={{flex:1}} placeholder="输入消息" disabled={sending}/>
        <Button type="primary" onClick={()=>{ send({ type:'text', content:input }); setInput(''); }} loading={sending} disabled={!input.trim()}>发送</Button>
        <Upload beforeUpload={beforeUpload} showUploadList={false} accept="image/*">
          <Button icon={<UploadOutlined />} loading={sending}>图片</Button>
        </Upload>
      </Space>
    </Card>
  );
};
export default ConsultChat;
